package com.pfc.wifis;

import java.util.ArrayList;
import java.util.List;

import com.pfc.files.FileManager;
import com.pfc.wifis.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;


public class GuardarLocalizacion extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
	private Button buttonScan;
	private EditText lugar;
	private ArrayList<Object> listaLecturas;
	private ProgressBar pBar;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guardar_localizacion);
        this.buttonScan = (Button)findViewById(R.id.button_scan);
        this.buttonScan.setOnClickListener(this);
        this.buttonScan.setText("Iniciar Escaneo");
        this.lugar = (EditText)findViewById(R.id.nombre_lugar);
        this.listaLecturas = new ArrayList<Object>();
        
    }

	@Override
	public void onClick(View v) {
		String place = lugar.getText().toString();
		switch (v.getId()){
		case (R.id.button_scan):
			if (this.buttonScan.getText().equals("Iniciar Escaneo")){
				Toast.makeText(this, "Escaneando redes wifi...", Toast.LENGTH_LONG).show();
				//tarea, timer task
				listaLecturas.add(scanWifis(place));
				//this.pBar.setVisibility(View.VISIBLE);
				this.buttonScan.setText("Parar Escaneo");
				
			}
			else{
				//this.pBar.setVisibility(View.GONE);
				Toast.makeText(this, "Guardando redes wifi...", Toast.LENGTH_LONG).show();
				String sd = Environment.getExternalStorageDirectory().getAbsolutePath();
				FileManager fm = new FileManager(sd, place);
				fm.WriteFile(listaLecturas);
				this.buttonScan.setText("Iniciar Escaneo");
			}
			break;
		}
	}
	
	public ArrayList<Element> scanWifis(String place){
		WifiManager manWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        manWifi.startScan();
        List<ScanResult> wifiList = manWifi.getScanResults();
        ArrayList<Element> lectura = new ArrayList<Element>();
	    for(int i = 0; i < wifiList.size(); i++){
	    		String ssid  = wifiList.get(i).SSID;
	    		String power = Integer.toString(wifiList.get(i).level);
	    		String frec  = Integer.toString(wifiList.get(i).frequency);
	    		lectura.add(new Element(ssid, power, frec, place)); 
	   	}   
	    return lectura;
	}
	
	
}
